package cn.gjxblog.transaction;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * 嵌套异常测试
 */
public class NestTransactionTests {

    @Test
    public void test(){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(AnnotationTransactionTests.RootConfig.class, AnnotationTransactionConfig.class);
        context.register(UserService.class,PersonService.class);
        context.refresh();

        UserService userService = context.getBean( UserService.class);
        userService.create();
    }

    @Configuration
    @EnableTransactionManagement
    static class AnnotationTransactionConfig{
    }

    @Service
    static class UserService{
        @Autowired
        PersonService personService;

        @Transactional
        public boolean create() {
            int i =1;
            try {
                personService.addPerson();
            } catch (Exception e) {
                // 设置已经手动回滚，这样上层就无需去处理异常
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }

            return i == 1;
        }
    }
    @Service
    static class PersonService{
        @Transactional
        public boolean addPerson() {
            System.out.println(1 / 0);
            return false;
        }
    }





}
